<?php
namespace App\Services\Sms;

use App\Services\HttpAbstract;

class Smser extends HttpAbstract implements SmsContract
{

	/**
	 * HTTP请求超时时间
	 */
	protected $timeout = 5;

	/**
	 * 发送短信
	 */
	public function send($mobile, $content)
	{
		// 忽略单元测试环境。
		if (app()->runningUnitTests()) {
			return false;
		}


		// 发送短信地址，以下为示例地址，具体地址询问网关获取
		$url_send_sms = "http://43.243.130.33:8860/sendSms";
        $url_send_sms_bak = "http://121.42.10.184:8860/sendSms";
		// 用户账号，必填
		$cust_code = "300432";
		// 用户密码，必填
		$cust_pwd = "ZMLH3N6KTG";
		// 接收号码，必填，同时发送给多个号码时,号码之间用英文半角逗号分隔
		$destMobiles = $mobile;
		// 业务标识，选填，由客户自行填写不超过20位的数字
		$uid = "";
		// 长号码，选填
		$sp_code = "";
		// 是否需要状态报告
		$need_report = "yes";
		// 签名，签名内容根据 “短信内容+客户密码”进行MD5编码后获得
		$sign = $content.$cust_pwd;
		$sign = md5($sign);
		$ch = curl_init();
		/* 设置验证方式 */
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','charset=utf-8'));
		/* 设置返回结果为流 */
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		/* 设置超时时间*/
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
		/* 设置通信方式 */
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		// 发送短信
		$data=array('cust_code'=>$cust_code,'sp_code'=>$sp_code,'content'=>$content,'destMobiles'=>$destMobiles,'uid'=>$uid,'need_report'=>$need_report,'sign'=>$sign);
		$json_data = json_encode($data);
		$resp_data = $this->sendSms($ch,$json_data,$url_send_sms);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//		curl_close($ch);
        $resp_data = json_decode($resp_data,true);
        if($httpCode!= 200 || (isset($resp_data['status']) && $resp_data['status'] != 'success')){
            $this->sendSms($ch,$json_data,$url_send_sms_bak);
        }
        curl_close($ch);
	}

	/**
	 * GET方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpGet($url, $data = [])
	{
		return $this->httpRequest('GET', $url, $data);
	}

	/**
	 * POST方法请求HTTP
	 *
	 * @param string $url
	 * @param array $data
	 */
	protected function httpPost($url, $data = [])
	{
		return $this->httpRequest('POST', $url, $data);
	}

	/**
	 * 基础HTTP请求实现
	 * @param string $method
	 * @param string $url
	 * @param array $data
	 * @return string
	 */
	private function httpRequest($method, $url, $data)
	{
		$method = strtoupper($method);
		if (! in_array($method, [
			'GET',
			'POST'
		])) {
			$method = 'GET';
		}

		$response = false;
		try {

			$data = http_build_query($data);

			$opts = [
				'http' => [
					'method' => $method,
					'timeout' => $this->timeout
				]
			];

			switch ($method) {
				case 'GET':
					$url .= strpos($url, '?') === false ? '?' : '&';
					$url .= $data;
					break;
				case 'POST':
					$opts['http']['header'] = "Content-type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($data) . "\r\n";
					$opts['http']['content'] = $data;
					break;
			}

			$context = stream_context_create($opts);
			$response = file_get_contents($url, false, $context);
		} catch (\Exception $e) {
			// 捕获异常。
			// throw $e;
			// TODO: 记录错误日志，静默处理。
		}

		// 剔除前后空格。
		$response = preg_replace('/^\\s+|\\s+$/', '', $response);

		return $response;
	}

	function sendSms($ch,$data,$send_url){
		curl_setopt ($ch, CURLOPT_URL, $send_url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		return curl_exec($ch);
	}
}
